package com.chinaunicom.jdbc;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SingleColumnRowMapper;
import org.springframework.jdbc.core.StatementCallback;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2022/1/14 9:21
 * Description:
 */
public class OrderServiceImpl implements OrderService {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }


    @Override
    public void save(Order order) {
        jdbcTemplate.update("insert into data_order(id,name,count) values(?,?,?)",
                new Object[]{order.getId(), order.getName(), order.getCount()},
                new int[]{Types.VARCHAR, Types.VARCHAR, Types.INTEGER});
    }

    @Override
    public List<Order> list() {
        return jdbcTemplate.query("select * from data_order", new OrderRowMapper());
    }

    @Override
    public List<Order> select() {
        // TODO: 创建一般的 Statement
        return jdbcTemplate.query("select * from  data_order", new BeanPropertyRowMapper<>(Order.class));
    }

    @Override
    public List<Map<String, Object>> findAll() {
//        return jdbcTemplate.queryForMap("select * from data_order");
        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from data_order");
        return maps;
    }

    @Override
    public List<String> selectIds() {
        return jdbcTemplate.queryForList("select id from data_order", String.class);
    }


    @Override
    public Order getOne(String id) {
        // TODO: 这里创建预编译 PreparedStatement对象
        return jdbcTemplate.queryForObject("select * from data_order where id = ?",
                new Object[]{id},
                new int[]{Types.VARCHAR},
                new BeanPropertyRowMapper<>(Order.class));

    }


}
